package redarrow.wb.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import redarrow.wb.util.DBConfig;
import redarrow.wb.util.IConstants;

public class UrlDao {

	public static DBConfig dbc = new DBConfig();

	public static String[] getUserUrls(String username) throws SQLException,
			ClassNotFoundException, IOException {
		// TODO Auto-generated method stub
		String[] urlList = null;
		List<String> lst = new ArrayList<String>();
		dbc.loadProperties();
		String url = DBConfig.db_url;
		String account = DBConfig.db_account;
		String pass = DBConfig.db_password;
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection(url, account, pass);
		Statement stmt = con.createStatement();
		ResultSet result = stmt
				.executeQuery("SELECT tbl_url.url_address FROM tbl_url INNER JOIN tbl_user ON url_user_id = user_id AND username='"
						+ username + "'");
		while (result.next()) {
			lst.add(result.getString("url_address"));

		}
		urlList = lst.toArray(new String[lst.size()]);
		con.close();

		return urlList;
	}

	public static int addUrl(String username, String urlAddress,
			String urlGendate, String status) {
		try {
			dbc.loadProperties();
			String url = DBConfig.db_url;
			String account = DBConfig.db_account;
			String pass = DBConfig.db_password;			
			int urlUserId = UserDao.getUserFromUsername(username);
			if (urlUserId == IConstants.USER_NOT_EXIST){
				return IConstants.USER_NOT_EXIST;
			}
			String insert = "INSERT INTO tbl_url(url_address, url_user_id, url_gendate, status)"
					+ "VALUES (?, ?, ?, ?)";
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url, account, pass);
			PreparedStatement ps = con.prepareStatement(insert);
			ps.setString(1, urlAddress);
			ps.setInt(2, urlUserId);
			ps.setString(3, urlGendate);
			ps.setString(4, status);
			ps.executeUpdate();
			con.close();

		} catch (SQLException ex) {
			ex.printStackTrace();
			return IConstants.SQLException;

		} catch (ClassNotFoundException e) {

			return IConstants.CLASS_NOT_FOUND;
			 //e.printStackTrace();
		} catch (IOException e) {

			return IConstants.IOException;
			// e.printStackTrace();
		}
		return IConstants.SUCCESS;
	}

	public static void main(String args[]) {
		/*String[] lst = null;
		try {
			lst = getUserUrls("hongson");
			System.out.println(lst[0]);
			System.out.println(lst[1]);
		} catch (ClassNotFoundException | SQLException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		int s= addUrl("hongso1n", "sss", "now", "1");
		System.out.println(s);
	}
}
